var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var isRefresh = false;
var _limitMenu = system.MENULIMIT.WECHAT02;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'wx/product/page';

var Utils = {
	doQueryProductType : function(){
		commonDia = $.dialog({
			title : '选择商品分类',
			content : 'url:'+config.BASEPATH+'wx/producttype/to_list_dialog',
			data : {multiselect:false},
			width : 350,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#wp_pt_code").val(selected.pt_code);
				$("#pt_name").val(selected.pt_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#wp_pt_code").val(selected.pt_code);
					$("#pt_name").val(selected.pt_name);
				}
			},
			cancel:true
		});
	}
};

var handle = {
	operate: function(oper, id){//修改、新增
		if(oper == 'add'){
			url = config.BASEPATH+"wx/product/to_add";
			data = {oper: oper, callback:this.callback};
		}else if(oper == 'edit'){
			url = config.BASEPATH+"wx/product/to_update?wp_id="+id;
			data = {oper: oper,callback: this.callback};
		}else if(oper == 'view'){
			url = config.BASEPATH+"shop/want/to_view?wt_id="+id;
			data = {oper: oper,callback: this.callback};
		}else{
			return false;
		}
		$.dialog({
			title : false,
			content : 'url:'+url,
			data: data,
			max : false,
			min : false,
			cache : false,
			lock: false
		}).max();
	},
 	updateState:function(obj,rowId,state){
		var tip = "";
		if(state == "1"){
			tip += "确认要下架该商品吗？";
		}else{
			tip += "确认要上架该商品吗？";
		}
		$.dialog.confirm(tip, function(){
			$.ajax({
				type:"POST",
				url:config.BASEPATH+'wx/product/updateState',
				data:{'wp_id':rowId,"wp_state":state},
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						$("#grid").jqGrid("setRowData", rowId,{wp_state:state});
						if(state == "1"){
							$(obj).html("&#xe63c;").removeClass("ui-icon-xiajia").addClass("ui-icon-shangjia").attr("title","上架")
						}else{
							$(obj).html("&#xe63e;").removeClass("ui-icon-shangjia").addClass("ui-icon-xiajia").attr("title","下架");
						}
					}else{
						Public.tips({type: 1, content : data.message});
					}
				}
			});
		});
    },
	del: function(rowId){//删除
		var rowData = $("#grid").jqGrid("getRowData", rowId);
	 	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
			$.ajax({
				type:"POST",
				url:config.BASEPATH+'wx/product/del',
				data:{"wp_id":rowId,"wp_number":rowData.wp_number},
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						Public.tips({type: 3, content : '删除成功!'});
						$('#grid').jqGrid('delRowData', rowId);
					}else{
						Public.tips({type: 1, content : data.message});
					}
				}
			});
		});	
    },
    addImage: function(id){//新增图片
    	var rowData = $("#grid").jqGrid("getRowData", id);
		$.dialog({ 
			id: 'id',
			title: '商品图片',
			max: false,
			min: false,
			width: '830px',
			height: '400px',
			fixed:false,
			drag: true,
			content:'url:'+config.BASEPATH+'base/product/to_img_add?pd_code='+rowData.wp_pd_code
		});
    },
    updateShop: function(id){//新增图片
    	var rowData = $("#grid").jqGrid("getRowData", id);
    	commonDia = $.dialog({ 
			id: 'id',
			title: '关联店铺',
			data:{wp_number:rowData.wp_number},
			max: false,
			min: false,
			width : 280,
		   	height : 320,
			fixed:false,
			drag: true,
			content:'url:'+config.BASEPATH+'wx/product/to_shop_update_tree',
			ok:function(){
				var selected = commonDia.content.doSelect();
				var shop_codes = [];
				for(var i=0;i<selected.length;i++){
					shop_codes.push(selected[i].sp_code);
				}
				$.ajax({
					type:"POST",
					url:config.BASEPATH+'wx/product/updateShop',
					data:{"wp_number":rowData.wp_number,"shop_codes":shop_codes.join(",")},
					cache:false,
					dataType:"json",
					success:function(data){
						if(undefined != data && data.stat == 200){
							Public.tips({type: 3, content : '关联店铺成功'});
							commonDia.close();
						}else{
							Public.tips({type: 1, content : data.message});
						}
					}
				});
				return false;
			},
			cancel:true
		});
    },
    qrcode: function(id){//新增图片
    	var rowData = $("#grid").jqGrid("getRowData", id);
    	commonDia = $.dialog({ 
			id: 'qrcode',
			title: '商品二维码',
			data:{pd_no:rowData.pd_no,wp_pd_name:rowData.wp_pd_name},
			max: false,
			min: false,
			width : 440,
		   	height : 260,
			fixed:false,
			drag: true,
			content:'url:'+config.BASEPATH+'wx/product/to_qrcode',
			ok:function(){
			},
			cancel:true
		});
    },
    callback: function(data, oper, dialogWin){
		if(oper == "edit") {
			THISPAGE.reloadData();
			dialogWin && dialogWin.api.close();
		}
		if(oper == "view") {
			$("#grid").jqGrid('setRowData', data.id, data);
			dialogWin && dialogWin.api.close();
		}
		if(oper == "add"){
			THISPAGE.reloadData();
			dialogWin && dialogWin.api.close();
		}
	},
	operFmatter : function(val, opt, row){
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		
		if(row.wp_state == '0'){//已上架---下架操作
			html_con += '<i class="iconfont i-hand ui-icon-xiajia" title="下架">&#xe63e;</i>';
		}else if(row.wp_state == '1'){//已下架---上架操作
			html_con += '<i class="iconfont i-hand ui-icon-shangjia" title="上架">&#xe63c;</i>';
		}
		html_con += '<i class="iconfont i-hand ui-icon-pencil" title="修改">&#xe60c;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-image" title="图片">&#xe654;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-qrcode" title="商品二维码">&#xe617;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-shop" title="关联店铺">&#xe610;</i>';
		html_con += '</div>';
		return html_con;
	},
	formatState:function(val, opt, row){
		if(val == 0){
			return '上架';
		}else if(val == 1){
			return '下架';
		}
		return val;
	},
	formatType:function(val, opt, row){//商品类型：0-正常商品，1-新品，2-折扣商品
		if(val == 0){
			return '正常商品';
		}else if(val == 1){
			return '新品';
		}else if(val == 2){
			return '折扣商品';
		}
		return val;
	},
	formatIsBuy:function(val, opt, row){
		if(val == 0){
			return '否';
		}else if(val == 1){
			return '是';
		}
		return val;
	},
	formatBuyWay:function(val, opt, row){
		if(val == ''){
			return '';
		}
		var result = '';
		if (val.indexOf('0') > -1) {
			result += '快递取货,'
		}
		if (val.indexOf('1') > -1) {
			result += '上门自取,'
		}
		if(result.length > 0){
			result = result.substring(0, result.length-1);
    	}
		return result;
	},
	formatPostFree:function(val, opt, row){
		if(val == '0'){
			return '否';
		}else if(val == '1'){
			return '是';
		}
		return '';
	},
	formatIsTry:function(val, opt, row){
		if(val == 0){
			return '否';
		}else if(val == 1){
			return '是';
		}
		return val;
	},
	formatTryWay:function(val, opt, row){//0-到店试穿，1-送货上门试穿
		if(val == ''){
			return '';
		}
		var result = '';
		if (val.indexOf('0') > -1) {
			result += '到店试穿,'
		}
		if (val.indexOf('1') > -1) {
			result += '送货上门,'
		}
		if(result.length > 0){
			result = result.substring(0, result.length-1);
    	}
		return result;
	},
	formatGapAmount:function(val, opt, row){
		return row.wt_applyamount-row.wt_sendamount;
	}
};

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();	
	},
	initDom:function(){
		this.$_date = $("#date").cssRadio({ callback: function($_obj){
			dateRedioClick($_obj.find("input").attr("id"));
		}});
		this.$_wp_type = $("#td_wp_type").cssRadio({ callback: function($_obj){
			$("#wp_type").val($_obj.find("input").val());
		}});
		this.$_wp_istry = $("#td_wp_istry").cssRadio({ callback: function($_obj){
			$("#wp_istry").val($_obj.find("input").val());
		}});
		this.$_wp_state = $("#td_wp_state").cssRadio({ callback: function($_obj){
			$("#wp_state").val($_obj.find("input").val());
		}});
	},
	initGrid:function(){
		var gridWH = Public.setGrid();
		var colModel = [
	    	{label:'操作',name: 'operate',width: 120, formatter: handle.operFmatter,align:'center', sortable:false},
	    	{label:'',name: 'wp_number',index: 'wp_number',width:100,hidden:true},
	    	{label:'',name: 'wp_pd_code',index: 'wp_pd_code',width:100,hidden:true},
	    	{label:'商品货号',name: 'pd_no',index: 'pd_no',width:100},
	    	{label:'商品名称',name: 'wp_pd_name',index: 'wp_pd_name',width:150},
	    	{label:'零售价',name: 'wp_sell_price',index: 'wp_sell_price',width:80,formatter: PriceLimit.formatMoney,align:'right'},
	    	{label:'折扣价',name: 'wp_rate_price',index: 'wp_rate_price',width:80,formatter: PriceLimit.formatMoney,align:'right'},
	    	{label:'分类名称',name: 'wp_pt_name',index: 'wp_pt_name',width:80},
	    	{label:'品牌',name: 'pd_bd_name',index: 'pd_bd_name',width:80},
	    	{label:'季节',name: 'pd_season', index: 'pd_season', width: 60},
	    	{label:'年份',name: 'pd_year', index: 'pd_year', width: 60},
	    	{label:'款式',name: 'pd_style', index: 'pd_style', width: 60},
	    	{label:'面料',name: 'pd_fabric', index: 'pd_fabric', width: 60},
	    	{label:'状态',name: 'wp_state',index: 'wp_state',width:60,formatter: handle.formatState,align:'center'},
	    	{label:'商品类型',name: 'wp_type',index: 'wp_type',width:80,formatter: handle.formatType,align:'center'},
	    	{label:'是否购买',name: 'wp_isbuy',index: 'wp_isbuy',width:60,formatter: handle.formatIsBuy,align:'center'},
	    	{label:'购买取货方式',name: 'wp_buy_way',index: 'wp_buy_way',width:100,formatter: handle.formatBuyWay},
	    	{label:'是否包邮',name: 'wp_postfree',index: 'wp_postfree',width:60,formatter: handle.formatPostFree,align:'center'},
	    	{label:'是否试穿',name: 'wp_istry',index: 'wp_istry',width:60,formatter: handle.formatIsTry,align:'center'},
	    	{label:'试穿方式',name: 'wp_try_way',index: 'wp_try_way',width:100,formatter: handle.formatTryWay},
	    	{label:'商品属性',name: 'wp_property_name', index: 'wp_property_name', width: 150},
	    	{label:'售后承诺',name: 'wp_promise_name', index: 'wp_promise_name', width: 150},
	    	{label:'副标题',name: 'wp_subtitle', index: 'wp_subtitle', width: 150}
	    ];
		$('#grid').jqGrid({
            url:queryurl+'?'+THISPAGE.buildParams(),			
			datatype: 'json',
			width: gridWH.w-12,
			height: gridWH.h-20,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:config.BASEROWNUM,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
				repeatitems : false,
				id: 'wp_id'  //图标ID
			},
			loadComplete: function(data){
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	buildParams : function(){
		var params = '';
		params += 'wp_type='+$("#wp_type").val();
		params += '&wp_istry='+$("#wp_istry").val();
		params += '&wp_state='+$("#wp_state").val();
		params += '&begindate='+$("#begindate").val();
		params += '&enddate='+$("#enddate").val();
		params += '&wp_pt_code='+$("#wp_pt_code").val();
		params += '&pd_no='+Public.encodeURI($("#pd_no").val());
		params += '&pd_name='+Public.encodeURI($("#pd_name").val());
		return params;
	},
	reset:function(){
		$("#wp_pt_code").val("");
		$("#pd_no").val("");
		$("#pd_name").val("");
		$("#pt_name").val("");
		THISPAGE.$_date.setValue(0);
		THISPAGE.$_wp_type.setValue(0);
		THISPAGE.$_wp_istry.setValue(0);
		THISPAGE.$_wp_state.setValue(0);
		$("#begindate").val("");
		$("#enddate").val("");
	},
	reloadData:function(){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			THISPAGE.reloadData();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		//新增
		$('#btn-add').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.INSERT)) {
				return ;
			}
			handle.operate('add');
		});
		$('#btn-del').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
				return ;
			}
			var rowId = $('#grid').jqGrid('getGridParam','selrow');
			if(rowId == null || rowId == ''){
				Public.tips({type: 1, content : "您未选择任何数据"});
				return;
			}
			var rowData =$("#grid").jqGrid("getRowData", rowId);
			if(rowData.wt_ar_state != "未审核" && rowData.wt_ar_state != "已退回"){
				Public.tips({type: 1, content : "单据已审核，不能删除"});
				return;
			}
			handle.del(rowId)
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
		//修改
		$('#grid').on('click', '.operating .ui-icon-pencil', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.UPDATE)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.operate('edit',id);
		});
		
		//下架
		$('#grid').on('click', '.operating .ui-icon-xiajia', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.UPDATE)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.updateState(this,id, "1");
		});
		//上架
		$('#grid').on('click', '.operating .ui-icon-shangjia', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.UPDATE)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.updateState(this,id, "0");
		});
		//删除
		$('#grid').on('click', '.operating .ui-icon-trash', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.del(id);
		});
		$('#grid').on('click', '.operating .ui-icon-image', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.UPDATE)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.addImage(id);
		});
		$('#grid').on('click', '.operating .ui-icon-shop', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.UPDATE)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.updateShop(id);
		});
		$('#grid').on('click', '.operating .ui-icon-qrcode', function(e){
			e.preventDefault();
			var id = $(this).parent().data('id');
			handle.qrcode(id);
		});
	}
}
THISPAGE.init();